package com.own.business.exam.business.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.own.business.exam.business.service.ExamPaperService;
import com.own.business.exam.business.service.ExamRuleAccountService;
import com.own.business.exam.entity.po.ExamPaper;
import com.own.business.exam.entity.po.ExamRule;
import com.own.business.exam.entity.po.ExamRuleAccount;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * ExamRuleUtil
 *
 * @author chenxueli
 * @date 2021/5/18 15:03
 */
@Component
public class ExamRuleUtil {

    @Resource
    private ExamPaperService examPaperService;
    @Resource
    private ExamRuleAccountService examRuleAccountService;

    /**
     * 验证考试是否可以获取
     *
     * @param ruleList 规则列表
     * @param account  账号信息
     * @return 匹配的规则
     */
    public ExamRule matchRule(List<ExamRule> ruleList, String account) {
        for (var rule : ruleList) {
            // 指定人数且考试最多容纳的人数大于0
            if (rule.getIsAssignNumber() == 1 && rule.getAssignNumber() > 0) {
                var count = examPaperService.countEqual(ExamPaper::getFkRuleId, rule.getId());
                if (rule.getAssignNumber() <= count) {
                    continue;
                }
            }
            // 判断是否在指定账号内
            if (rule.getIsAssignAccount() == 1 && examRuleAccountService.getOneByWrapper(new QueryWrapper<ExamRuleAccount>().lambda()
                    .eq(ExamRuleAccount::getFkRuleId, rule.getId())
                    .eq(ExamRuleAccount::getFkRuleId, account)) == null) {
                continue;
            }
            return rule;
        }
        return null;
    }

}
